package servlet;

import com.alibaba.fastjson.JSON;
import dao.DAO;
import domain.Commodity;
import domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/GoodsServlet")
public class GoodsServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String type=request.getParameter("type");
        if("findAll_goods".equals(type)){
            getAllGoods(request,response);
        }else if ("query_goods".equals(type)){
            queryGoods(request,response);
        }else if("show_picture".equals(type))
            showPicture(request,response);
            
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    DAO dao = new DAO();

    public void getAllGoods(HttpServletRequest request, HttpServletResponse response) {
        List<Commodity> list = dao.getAllGoods();//获取所有商品信息
        String listStr = JSON.toJSONString(list);

        try {
//            System.out.println(listStr);
            response.getWriter().print(listStr);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //TODO
    private void showPicture(HttpServletRequest request, HttpServletResponse response) {
        int id=Integer.parseInt(request.getParameter("id"));


    }
    
    public void queryGoods(HttpServletRequest request, HttpServletResponse response){
        String name=request.getParameter("id");
        List<Commodity> list = dao.findByName(name);
        //3.把数据结果返回客户端
        String listStr = JSON.toJSONString(list);

        try {
            response.getWriter().print(listStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
